﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace AirLine.DataAccess
{
    public class Repository : IRepository
    {
        private DbContext entities;

        public Repository(DbContext entities)
        {            
            entities.Configuration.LazyLoadingEnabled = false;
            entities.Configuration.ProxyCreationEnabled = false;
            this.entities = entities;
        }

        public IEnumerable<T> Get<T>(
            Expression<Func<T, bool>> filter = null,
            Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
            string includeProperties = "") where T : class
        {
            IQueryable<T> query = entities.Set<T>();

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            return query.ToList();
        }

        public T GetById<T>(int id) where T : class
        {
            return entities.Set<T>().Find(id);
        }

        public IEnumerable<T> GetAll<T>() where T : class
        {
            return entities.Set<T>().AsEnumerable();
        }

        public bool Update<T>(T t) where T : class
        {
            entities.Entry(t).State = EntityState.Modified;
            return entities.SaveChanges() > 0;

        }

        public bool Add<T>(T t) where T : class
        {
            entities.Set<T>().Add(t);
            return entities.SaveChanges() > 0;
        }

        public bool Delete<T>(T t) where T : class
        {
            entities.Set<T>().Remove(t);
            return entities.SaveChanges() > 0;
        }

        public void AddWithOutCommit<T>(T t) where T : class
        {
            entities.Set<T>().Add(t);
        }
        public void Commit()
        {
            entities.SaveChanges();
        }
    }
}
